<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信二维码关注</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .title {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        .qrcode-section {
            text-align: center;
            margin: 30px 0;
        }
        .qrcode-img {
            max-width: 300px;
            border: 2px solid #ddd;
            border-radius: 8px;
            margin: 20px 0;
        }
        .btn {
            background-color: #07c160;
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            border-radius: 6px;
            cursor: pointer;
            margin: 10px;
        }
        .btn:hover {
            background-color: #06ad56;
        }
        .btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .status {
            margin: 20px 0;
            padding: 15px;
            border-radius: 6px;
            font-weight: bold;
        }
        .status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .logs {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 14px;
        }
        .log-item {
            margin: 5px 0;
            padding: 5px;
            border-left: 3px solid #007bff;
            background-color: white;
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #07c160;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">微信服务号二维码关注</h1>

        <div class="qrcode-section">
            <div id="loading-container">
                <h3>正在生成二维码...</h3>
                <div class="loading-spinner"></div>
            </div>
            <div id="qrcode-container" style="display: none;">
                <h3>请使用微信扫描下方二维码关注</h3>
                <img id="qrcode-img" class="qrcode-img" src="" alt="二维码">
                <p>场景值：<span id="scene-str"></span></p>
                <button class="btn" onclick="generateQrCode()" style="margin-top: 20px;">重新生成二维码</button>
            </div>
        </div>

        <div id="status" class="status" style="display: none;"></div>

        <div>
            <h3>实时日志</h3>
            <div id="logs" class="logs"></div>
        </div>
    </div>

    <script>
        let websocket = null;
        let currentSceneStr = null;
        let websocketBaseUrl = null;

        // 获取WebSocket配置
        function getWebSocketConfig() {
            return fetch('/api/websocket/config')
                .then(response => response.json())
                .then(data => {
                    websocketBaseUrl = data.websocketUrl;
                    addLog('获取WebSocket配置成功：' + websocketBaseUrl);
                })
                .catch(error => {
                    addLog('获取WebSocket配置失败：' + error.message);
                    // 如果获取配置失败，使用默认的本地配置
                    websocketBaseUrl = 'ws://127.0.0.1:8095/websocket';
                });
        }

        function generateQrCode() {
            // 显示加载状态
            document.getElementById('loading-container').style.display = 'block';
            document.getElementById('qrcode-container').style.display = 'none';

            const sceneValue = 'demo_' + Date.now();

            fetch('/wechat/create-qrcode', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    sceneValue: sceneValue,
                    expireSeconds: 1800
                })
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载状态
                document.getElementById('loading-container').style.display = 'none';

                if (data.code === 200) {
                    const result = data.data;
                    currentSceneStr = result.sceneStr;

                    document.getElementById('qrcode-img').src = result.imageUrl;
                    document.getElementById('scene-str').textContent = result.sceneStr;
                    document.getElementById('qrcode-container').style.display = 'block';

                    showStatus('二维码生成成功！请使用微信扫码关注', 'success');
                    addLog('二维码生成成功，场景值：' + result.sceneStr);

                    // 建立WebSocket连接
                    connectWebSocket(result.sceneStr);
                } else {
                    showStatus('生成二维码失败：' + data.message, 'error');
                    addLog('生成二维码失败：' + data.message);
                }
            })
            .catch(error => {
                // 隐藏加载状态
                document.getElementById('loading-container').style.display = 'none';
                showStatus('请求失败：' + error.message, 'error');
                addLog('请求失败：' + error.message);
            });
        }

        function connectWebSocket(sceneStr) {
            if (websocket) {
                websocket.close();
            }

            // 如果还没有获取WebSocket配置，先获取
            if (!websocketBaseUrl) {
                getWebSocketConfig().then(() => {
                    establishWebSocketConnection(sceneStr);
                });
                return;
            }
            
            establishWebSocketConnection(sceneStr);
        }

        function establishWebSocketConnection(sceneStr) {
            const wsUrl = websocketBaseUrl + '/' + sceneStr;
            websocket = new WebSocket(wsUrl);

            websocket.onopen = function() {
                addLog('WebSocket连接已建立，等待用户扫码...');
                showStatus('等待用户扫码关注...', 'info');
            };

            websocket.onmessage = function(event) {
                const message = event.data;
                addLog('收到消息：' + message);

                if (message.includes('用户关注成功')) {
                    showStatus('用户关注成功！' + message, 'success');
                }
            };

            websocket.onclose = function() {
                addLog('WebSocket连接已关闭');
            };

            websocket.onerror = function(error) {
                addLog('WebSocket错误：' + error);
                showStatus('连接错误', 'error');
            };
        }

        function showStatus(message, type) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = 'status ' + type;
            statusDiv.style.display = 'block';
        }

        function addLog(message) {
            const logsDiv = document.getElementById('logs');
            const logItem = document.createElement('div');
            logItem.className = 'log-item';
            logItem.textContent = new Date().toLocaleTimeString() + ' - ' + message;
            logsDiv.appendChild(logItem);
            logsDiv.scrollTop = logsDiv.scrollHeight;
        }

        // 页面加载完成时先获取WebSocket配置，然后自动生成二维码
        window.addEventListener('DOMContentLoaded', function() {
            addLog('页面加载完成，获取WebSocket配置...');
            getWebSocketConfig().then(() => {
                addLog('配置获取完成，自动生成二维码...');
                generateQrCode();
            });
        });

        // 页面卸载时关闭WebSocket连接
        window.addEventListener('beforeunload', function() {
            if (websocket) {
                websocket.close();
            }
        });
    </script>
</body>
</html>
